<?php

namespace addons\shopro\job;

use addons\shopro\service\commission\Order as OrderService;
use addons\shopro\service\lucky\LuckyService;
use addons\shopro\service\user\User as UserService;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\commission\Agent;
use app\admin\model\shopro\lucky\Auto;
use app\admin\model\shopro\lucky\Autolog;
use app\admin\model\shopro\lucky\Server;
use app\admin\model\shopro\tokens\Config;
use app\admin\model\shopro\tokens\Node;
use app\admin\model\User;
use think\queue\Job;
use think\Db;
use think\exception\HttpResponseException;
use addons\shopro\service\commission\Reward as RewardService;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\user\User as UserModel;

/**
 * 分销任务
 */
class Commission extends BaseJob
{

    /**
     * 分销商升级
     */
    public function agentUpgrade(Job $job, $payload)
    {
        try {

            $userId = $payload['user_id'];
            $agent = new AgentService($userId);

            if ($agent->user) {
                Db::transaction(function () use ($agent) {
                    $agent->runAgentUpgradePlan();
                });

            }

            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            print($message);
            format_log_error($e, 'AgentUpgrade.HttpResponseException', $message);
        } catch (\Exception $e) {
            print($e->getMessage());
            format_log_error($e, 'AgentUpgrade');
        }
    }

    public function orderCommission(Job $job, $params)
    {
        // $job->delete();
        //$userLucky=$params;
        Db::startTrans();
        try {
            $userLucky = \app\admin\model\shopro\lucky\User::where(['id' => $params['id'], 'stutas' => '0'])->find();
            if ($userLucky) {

                $user = UserModel::get($userLucky['user_id']);
                if (!$user) {
                    \app\admin\model\shopro\lucky\User::where(['id' => $userLucky['id'], 'stutas' => '0'])->update(['stutas' => '1']);
                    Db::commit();
                    $job->delete();

                }

                if ($userLucky['score'] > 0) {
                    WalletService::change($userLucky['user_id'], 'score', $userLucky['score'], 'lucky_income');
                    UserModel::where('id', $userLucky['user_id'])->setInc('total_score', $userLucky['score']);
                    Agent::where('user_id', $userLucky['user_id'])->setInc('score_total_all', $userLucky['score']);
                }
                $money = $userLucky['total_price'] - $userLucky['p_total_price'];
                if ($money > 0) {
                    WalletService::change($userLucky['user_id'], 'money', $money, 'lucky_income');
                }
                if ($userLucky['commission'] > 0) {
                    WalletService::change($userLucky['user_id'], 'commission', $userLucky['commission'], 'lucky_income');
                    Agent::where('user_id', $userLucky['user_id'])->setInc('total_income', $userLucky['commission']);
                }

                if ($userLucky['gold_bean'] > 0) {
                    $config = sheep_config('shop.recharge_withdraw.withdraw');
                    $to_shopping = round((floatval($config['to_shopping']) * 0.01), 3);
                    $shoppingScore = 0;
                    $gold_bean = $userLucky['gold_bean'];
                    $total = $gold_bean;
                    if ($to_shopping > 0) {
                        $shoppingScore = bcmul($gold_bean, $to_shopping, 2);
                        $gold_bean = $gold_bean - $shoppingScore;
                    }
                    WalletService::change($userLucky['user_id'], 'gold_bean', $gold_bean, 'lucky_income');
                    Agent::where('user_id', $userLucky['user_id'])->setInc('total_income', $total);
                    if ($shoppingScore > 0) {
                        WalletService::change($userLucky['user_id'], 'shopping_score', $shoppingScore, 'lucky_income');
                    }

                }


                // 检查能否分销
                //if (!$commission->checkAndSetCommission()) continue;

                //空单不产生奖金
                if (sheep_config('shop.basic.bonus') != '0' && $user['order_switch'] == 0) {


                    // 订单支付成功
                    $order = $userLucky;
                    $commission = new OrderService($order);
                    // 添加分销订单
                    $commissionOrder = $commission->createCommissionOrder();
                    if ($commissionOrder) {
                        // 执行福利券计划
                        $commission->runCommissionPlan($commissionOrder);

                        // 支付后拨款
                        (new RewardService('paid'))->runCommissionRewardByOrder($commissionOrder);


                    }

                }


                \app\admin\model\shopro\lucky\User::where(['id' => $userLucky['id'], 'stutas' => '0'])->update(['stutas' => '1']);


            }
            Db::commit();
            $job->delete();
        } catch (HttpResponseException $e) {
            Db::rollback();
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'OrderCommissionAfter.HttpResponseException', $message);
        } catch (\Exception $e) {
            print($e->getMessage());
            Db::rollback();
            format_log_error($e, 'OrderCommissionAfter');
        }
    }

    public function tokensPlan(Job $job, $payload)
    {
        //$job->delete();
        try {

            $userId = $payload['user_id'];
            $userModel = UserModel::find($userId);
            $luckyService = new LuckyService();
            if ($userModel) {
                Db::transaction(function () use ($userModel, $luckyService, $payload) {

                    $luckyService->tokensPlan($userModel, $payload['tokens']);
                });

            }

            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            print($message);
            format_log_error($e, 'tokensPlan.HttpResponseException', $message);
        } catch (\Exception $e) {
            print($e->getMessage());
            format_log_error($e, 'tokensPlan');
        }
    }

    public function tokensNode(Job $job)
    {
        //$job->delete();
        try {

            $maxNodeCount = Node::where(['type' => 'max'])->count();
            $minNodeCount = Node::where(['type' => 'min'])->count();
            $cofing = Config::where(['id' => 1])->find();
            Db::transaction(function () use ($cofing, $minNodeCount, $maxNodeCount) {

                if ($maxNodeCount > 0 && $cofing['day_released'] > 0 && $cofing['max_node'] > 0) {
                    $max = bcmul($cofing['day_released'], $cofing['max_node'] / 100, 6);
                    $max_token = bcdiv($max, $maxNodeCount, 6);
                    Node::where(['type' => 'max'])->chunk(20, function ($item) use ($max_token) {

                        foreach ($item as $value) {
                            Node::where(['id' => $value['id']])->setInc('total_tokens', $max_token);
                            WalletService::change($value['user_id'], 'tokens', $max_token, 'score_node_release');
                        }

                    });
                }
                if ($minNodeCount > 0 && $cofing['day_released'] > 0 && $cofing['min_node'] > 0) {
                    $min = bcmul($cofing['day_released'], $cofing['min_node'] / 100, 6);
                    $min_token = bcdiv($min, $minNodeCount, 6);
                    Node::where(['type' => 'min'])->chunk(20, function ($item) use ($min_token) {
                        foreach ($item as $value) {
                            Node::where(['id' => $value['id']])->setInc('total_tokens', $min_token);
                            WalletService::change($value['user_id'], 'tokens', $min_token, 'score_node_release');
                        }

                    });

                }
            });


            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            print($message);
            format_log_error($e, 'tokensNode.HttpResponseException', $message);
        } catch (\Exception $e) {
            print($e->getMessage());
            format_log_error($e, 'tokensNode');
        }
    }

    public function autoLucky(Job $job)
    {
        //$job->delete();
        try {
            $luckyService = new LuckyService();
            $date = date('Y-m-d H:i:s');
            $server = Server::whereTime('start_time', '<=', $date)->whereTime('end_time', '>', $date)->where(['status' => 0])->find();
            Auto::whereTime('end_time', '>', $date)->chunk(20, function ($item) use ($date, $server, $luckyService) {

                foreach ($item as $value) {
                    $user = \app\admin\model\shopro\user\User::find($value['user_id']);
                    if ($user) {
                        $money = floor($user['money']);
                        $autolog = new Autolog();
                        $data = [
                            'user_id' => $value['user_id'],
                            'money' => 0,
                            'number' => 0,
                            'log' => '',
                            'status' => '1',
                            'createtime' => time()
                        ];
                        if ($server && $money >= $server['price']) {
                            $number = floor($money / $server['price']);
                            $data['number'] = $number;
                            $data['money'] = $money;
                            try {
                                if ($luckyService->auotSetLucky(['server_id' => $server['id'], 'number' => $number], $user)) {
                                    $data['log'] = '预约成功';
                                } else {
                                    $data['log'] = '预约失败';
                                    $data['status'] = '0';
                                }
                                $autolog->insert($data);
                            } catch (\Exception $e) {
                                $data['log'] = $e->getMessage();
                                $data['status'] = '0';
                                $autolog->insert($data);
                                continue;
                            }

                        } else {
                            $data['log'] = '余额不足';
                            $data['status'] = '0';
                            $autolog->insert($data);
                            continue;
                        }
                    }
                }
            });
            $job->delete();
        } catch (\Exception $e) {
            print($e->getMessage());
            format_log_error($e, 'tokensNode');
        }

    }


}
